package com.djhu.freepartner.web.control;

import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.web.entity.enums.Limit;
import com.djhu.freepartner.web.entity.enums.LimitType;
import com.djhu.freepartner.web.service.IFileService;
import com.google.common.base.Joiner;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadFileControl {

    private static Logger logger = LoggerFactory.getLogger(UploadFileControl.class.getName());


    @Autowired
    private IFileService fileService;


    @PostMapping("/upload")
    @Limit(name = "upload",limittype = LimitType.IP)
    @ApiOperation(value="上传文件", notes="上传文件")
    public RestRsp upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest httpServletRequest) throws ServiceException {
        String fileName = null;
        try {
            fileName = new String(multipartFile.getOriginalFilename().getBytes("GBK"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            fileName = multipartFile.getOriginalFilename();
        }
        logger.info("上传图片:size={},name={}",multipartFile.getSize(),fileName);
        //hash打散目录

        String url = fileService.store(multipartFile);
        RestRsp restRsp = new RestRsp();
        restRsp.setCode(Status.SUCCESS.getCode());
        Map<String,Object> map = new HashMap<>();
        map.put("url",url);
        restRsp.setData(map);
        logger.info("文件上传成功，ret url is {}",url);
        return restRsp;
    }

    private String getDir(String hashCodeHex) {
        return Joiner.on("/").join(hashCodeHex.charAt(0) ,hashCodeHex.charAt(1) ,hashCodeHex.charAt(2) ,hashCodeHex.charAt(3));
    }

}
